package com.journaldev.spring.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import com.journaldev.spring.model.Ward;

@Transactional
public class WardDAOImpl implements WardDAO {
	
	private static final Logger logger = LoggerFactory.getLogger(DistrictDAOImpl.class);

	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sf){
		this.sessionFactory = sf;
	}

	@Override
	public void addWard(Ward p) {
		// TODO Auto-generated method stub
		Session session = this.sessionFactory.getCurrentSession();
		session.persist(p);
		logger.info("Ward saved successfully, Ward Details="+p);
	}

	@Override
	public void updateWard(Ward p) {
		// TODO Auto-generated method stub
		Session session = this.sessionFactory.getCurrentSession();
		session.update(p);
		logger.info("Ward updated successfully, Ward Details="+p);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Ward> listWard() {
		// TODO Auto-generated method stub
		Session session = this.sessionFactory.getCurrentSession();
		List<Ward> wardList = session.createQuery("from Ward").list();
		for(Ward p : wardList){
			logger.info("Ward List::"+p);
		}
		return wardList;
	}

	@Override
	public Ward getWardById(int id) {
		// TODO Auto-generated method stub
		Session session = this.sessionFactory.getCurrentSession();		
		Ward p = (Ward) session.get(Ward.class, new Integer(id));
		logger.info("Ward loaded successfully, Ward details="+p);
		return p;
	}

	@Override
	public void removeWard(int id) {
		// TODO Auto-generated method stub
		Session session = this.sessionFactory.getCurrentSession();
		Ward p = (Ward) session.get(Ward.class, new Integer(id));
		if(null != p){
			session.delete(p);
		}
		logger.info("Ward deleted successfully, Ward details="+p);
	}

}
